﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using LearnNet.BLL;
using System.Xml;
using LearnNet.Common;
using System.Drawing;
using System.Reflection;
using Advertise;
using System.Threading;
using System.Collections;
using mshtml;
namespace Advertise
{
    public partial class FrmReport : Form
    {
        public FrmReport()
        {
            InitializeComponent();
        }
        #region  窗体居后
        [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SetWindowPos")]
        //import the native SetWindowPos function--导入SetWindowPos这个函数
        public static extern bool SetWindowPos(int hWnd,               // window handle      
            int hWndInsertAfter,    // placement-order handle      
            int X,                  // horizontal position      
            int Y,                  // vertical position      
            int cx,                 // width      
            int cy,                 // height      
            uint uFlags);           // window positioning flags   
        public const int HWND_BOTTOM = 0x1;
        public const uint SWP_NOSIZE = 0x1;
        public const uint SWP_NOMOVE = 0x2;
        public const uint SWP_SHOWWINDOW = 0x40;


        private void ShoveToBackground()
        {
            SetWindowPos((int)this.Handle, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
        }
        #endregion 

        protected RegistEntity regEntity = new RegistEntity();
        private XmlHelper xmlHelper = new XmlHelper(string.Concat(Application.StartupPath, "/config.xml"));
        private Thread threadOne;
        private DataTable dt = new DataTable();
        private ReportContent regContent = new ReportContent();
        private int state = 0;
        //加载当前url次数
        private int urlNum = 0;
        public System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
        /// <summary>
        /// 执行列表
        /// </summary>
        protected  UpdateInfo updateInfo = null;
        /// <summary>
        /// 注册信息列表
        /// </summary>
        public static List<RegistEntity> regeistEntitys = null;
        //private delegate void ShowTask(UpdateInfo upInfo);
        //private delegate void ThreadAbort(object sender, EventArgs e);


        public static List<RegistEntity> FailRegeistEntitys = null;

        private void Form2_Load(object sender, EventArgs e)
        {
            
            webBrowser1.ScriptErrorsSuppressed = false;
            
            // Control.CheckForIllegalCrossThreadCalls = false;
            this.webBrowser1.Navigating += new WebBrowserNavigatingEventHandler(webBrowser1_Navigating);
            this.webBrowser1.Navigated += new WebBrowserNavigatedEventHandler(webBrowser1_Navigated);
            (webBrowser1.ActiveXInstance as SHDocVw.WebBrowser).NavigateComplete2 += new SHDocVw.DWebBrowserEvents2_NavigateComplete2EventHandler(webBrowser1_Navigated2);
            this.webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
            this.webBrowser1.NewWindow += new CancelEventHandler(webBrowser1_NewWindow);
            
            timer.Tick += new EventHandler(timer_Tick);
            timer.Interval = 2000;
            timer.Enabled = false;
            BindList();
        
          
        }


        private void BindList()
        {
            regeistEntitys = new List<RegistEntity>();
            RegistEntity reg = new RegistEntity();
            //reg.Name = "yang0000meng";
            //reg.Pwd = "yang__2266452";
            //reg.Type = "Sina";
            //regeistEntitys.Add(reg);
            //reg = new RegistEntity();
            //reg.Name = "yang0000yang";
            //reg.Pwd = "qwe123456";
            //reg.Type = "Sohu";

            reg = new RegistEntity();
            reg.Name = "601588935@qq.com";
            reg.Pwd = "yang2266452";
            reg.Type = "51";
            regeistEntitys.Add(reg);

            //DataTable dt = new DataTable();
            //dt = LearnNet.DAL.DALHelper.LearnNetHelper.ExecuteQuery(CommandType.Text, "select * from userinfo order by orderNum asc  ", null);
            //if (dt == null)
            //{
            //    MessageBox.Show("请先注册");
            //    return;
            //}
            //for (int i = 0; i < dt.Rows.Count; i++)
            //{
            //    //if (dt.Rows[i]["website"].ToString().ToLower() == "sohu")
            //    //{
            //    reg = new RegistEntity();
            //    reg.Name = dt.Rows[i]["name"].ToString();
            //    reg.Pwd = dt.Rows[i]["pwd"].ToString();
            //    reg.Type = dt.Rows[i]["website"].ToString();
            //    reg.Num = i;
            //    regeistEntitys.Add(reg);
            //    //}
            //}
            label1.Text = "共有" + regeistEntitys.Count + "个";
            dt.Dispose();
            updateInfo = new UpdateInfo();
            updateInfo.Count = regeistEntitys.Count - 1;
            updateInfo.Index = -1;
           
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (tbTitile.Text == "")
            {
                MessageBox.Show("请填写标题");
                return;
            }
            if (tbContent.Text == "")
            {
                MessageBox.Show("请填写内容");
                return;
            }
            FailRegeistEntitys=  new List<RegistEntity>();
            regContent.Title = tbTitile.Text;
            regContent.Content = tbContent.Text;
            regContent.ClassType = "1";
            //ThreadDemo();
            //Start();
            state = 0;
            updateInfo.Index = -1;
            btnSend.Enabled = false;
            this.webBrowser1.Navigate("about:blank");
           
            btnJump.Text = "跳过(" + updateInfo.Index.ToString() + ")";
            
          
        }

        public  void timer_Tick(object sender, EventArgs e)
        {
          
               // this.webBrowser1.Document.Click += new HtmlElementEventHandler(Document_Click);

                string str = string.Empty;
                //UpdateInfo upInfo = new UpdateInfo();
                //upInfo.Count = dt.Rows.Count;
                //upInfo.Index = 0;
                string strSql = string.Empty;
                if (state == 0)
                {
                    
                    updateInfo.Index++;
                    label1.Text = "共有" + regeistEntitys.Count + "个" + "当前第：" + updateInfo.Index;
                    if (updateInfo.Index > updateInfo.Count)
                    {
                        btnSend.Enabled = true;
                        timer.Enabled = false;
                    
                        this.webBrowser1.Navigate("about:blank");
                        return;
                    }
                   
                }

                IRepost irepost = GetRepost(regeistEntitys[updateInfo.Index].Type) as IRepost;
                string strMessage = string.Empty;

            
               
                try
                {
                    Point p = new Point(100, 260);
                    webBrowser1.Document.Window.ScrollTo(p);
                    switch (state)
                    {
                        case 0:
                            {

                                webBrowser1.Url = new Uri(xmlHelper.GetAttribute("root/station[@code='" + regeistEntitys[updateInfo.Index].Type + "']/logout", "url").Replace("$0", regeistEntitys[updateInfo.Index].Name));
                                state = 1;
                                timer.Interval = 7000;
                                break;
                            }

                        case 1:
                            {
                                urlNum = 0;
                                webBrowser1.Url = new Uri(xmlHelper.GetAttribute("root/station[@code='" + regeistEntitys[updateInfo.Index].Type + "']/login", "url"));
                                state = 2;
                                timer.Interval = 7000;
                                break;
                            }
                        case 2:
                            {

                                if (webBrowser1.Url.AbsoluteUri == xmlHelper.GetAttribute("root/station[@code='" + regeistEntitys[updateInfo.Index].Type + "']/login", "url"))
                                {
                                    strMessage = irepost.LoginIn(webBrowser1, regeistEntitys[updateInfo.Index]);

                                    if (strMessage != "")
                                        tbError.Text = string.Concat(tbError.Text, "\r\n", strMessage);
                                    //   ReportHelper.HerfClick(webBrowser1, ");
                                    state = 3;
                                }
                                else
                                {
                                    urlNum = urlNum + 1;
                                    timer.Interval = 2000;
                                }
                                if (urlNum > 2)
                                {
                                    state = 3;
                                }
                                timer.Interval = 7000;
                                //timer.Enabled = false;
                                break;


                                  
                              
                                break;
                            }

                        case 3:
                            {
                                urlNum = 0;
                                webBrowser1.Url = new Uri(xmlHelper.GetAttribute("root/station[@code='" + regeistEntitys[updateInfo.Index].Type + "']/report", "url").Replace("$0", regeistEntitys[updateInfo.Index].Name));
                                state = 4;
                                timer.Interval = 8000;
                                break;
                            }
                        case 4:
                            {
                                if (webBrowser1.Url.AbsoluteUri == xmlHelper.GetAttribute("root/station[@code='" + regeistEntitys[updateInfo.Index].Type + "']/report", "url").Replace("$0", regeistEntitys[updateInfo.Index].Name))
                                {

                                    p = new Point(100, 760);
                                    webBrowser1.Document.Window.ScrollTo(p);
                                 
                                        
                                    strMessage = irepost.Report(webBrowser1, regContent);

                                    if (strMessage != "")
                                        tbError.Text = string.Concat(tbError.Text, "\r\n", strMessage);
                                    state = 0;
                                }
                                else
                                {
                                    urlNum = urlNum + 1;
                                    timer.Interval = 2000;
                                }
                                if(urlNum>2)
                                {
                                    state = 0;
                                }
                                
                                //timer.Enabled = false;
                                break;
                            }
                        //case 5:
                        //    {
                        //        timer.Interval = 2000;
                        //        webBrowser1.Url = new Uri(xmlHelper.GetAttribute("root/station[@code='" + regeistEntitys[updateInfo.Index].Type + "']/login", "url"));
                        //        state = 0;

                        //        break;
                        //    }

                        default:
                            {
                                timer.Enabled = false;
                                break;
                            }

                    }
                }
                catch (Exception ex)
                {
                    state = 0;
                    timer.Enabled = true;
                    tbError.Text = string.Concat(tbError.Text, "\r\n", ex.Message);
                    FailRegeistEntitys.Add(regeistEntitys[updateInfo.Index]);
                    label2.Text = string.Concat("发送失败共：", FailRegeistEntitys.Count);
                }
              
               
            
        }

      

        private void webBrowser1_Navigated2(object pDisp, ref object URL)
        {
            mshtml.IHTMLDocument2 doc = (webBrowser1.ActiveXInstance as SHDocVw.WebBrowser).Document as mshtml.IHTMLDocument2;
            doc.parentWindow.execScript("window.alert=null", "javascript");
            doc.parentWindow.execScript("window.confirm=null", "javascript");
            doc.parentWindow.execScript("window.open=null", "javascript");
            doc.parentWindow.execScript("window.showModalDialog=null", "javascript");
            doc.parentWindow.execScript("window.close=null", "javascript");
        }

       
        private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
           

            webBrowser1.ScriptErrorsSuppressed = false;
          
            string s = @"function confirm() {";
            s += @"return true;";
            s += @"}";
            s = @"function killerrors() { return true; } window.onerror = killerrors;window.confirm=null; ";

            s += @"function alert() {};";
            s += @"window.onbeforeunload = function(){};";

            //s += "window.alert = null; window.confirm = null;window.open = null;window.showModalDialog = null;";

             IHTMLDocument2 vDocument = (IHTMLDocument2)webBrowser1.Document.DomDocument;
            vDocument.parentWindow.execScript(s
                , "javaScript");

           
            foreach (IHTMLElement vElement in vDocument.all)
                if (vElement.tagName.ToUpper() == "IFRAME")
                {
                    IHTMLFrameBase2 vFrameBase2 = vElement as IHTMLFrameBase2;
                    vFrameBase2.contentWindow.execScript(
                        s, "javaScript");
                }
            
        }
        //protected void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        //{
        //    webBrowser1.ScriptErrorsSuppressed = false;
        //    HtmlDocument hd = webBrowser1.Document;
        //    IHTMLWindow2 win = (IHTMLWindow2)hd.Window.DomWindow;
        //    string s = @"function confirm() {";
        //    s += @"return true;";
        //    s += @"}";
        //    s = @"function killerrors() { return true; } window.onerror = killerrors; ";

        //    s += @"function alert() {};";
        //    s += @"window.onbeforeunload = function(){};";

        //    s += "window.alert = null; window.confirm = null;window.open = null;window.showModalDialog = null;";
        //    win.execScript(s, "javascript");


        //    //禁用js弹出窗
        //    //HtmlDocument hd = webBrowser1.Document;
        //    //    IHTMLWindow2 win = (IHTMLWindow2)hd.Window.DomWindow;
        //    //    string s = @"function confirm() {";
        //    //    s += @"return true;";
        //    //    s += @"}";
        //    //    s = @"function killerrors() { return true; } window.onerror = killerrors; ";
        //    //    s += @"function alert() {}";
        //    //    s += @"window.onbeforeunload = function(){}; ";
        //    //    win.execScript(s, "javascript");

        //}
    
       


        protected void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
           

            if (e.Url.ToString() != webBrowser1.Url.ToString())
                return;
           
            if (webBrowser1.ReadyState.ToString() == WebBrowserReadyState.Complete.ToString())
            {

                this.webBrowser1.Document.Window.Error += new HtmlElementErrorEventHandler(Window_Error);

                if (updateInfo.Index > updateInfo.Count)
                {
                    timer.Enabled = false;
                    btnSend.Enabled = true;
                }
                else
                {
                    if(!timer.Enabled)
                    {
                        timer.Enabled = true;
                    }
                    timer.Interval = 1000;
                    
                }
            
             

                //  MessageBox.Show(webBrowser1.ReadyState.ToString());

                // 在WebBrowser的DocumentComplete中写下面的代码。 
                //触发事件
                //IHTMLDocument2 m_pHtmlDoc2 = (IHTMLDocument2)hd.DomDocument;
                //HTMLDocumentEvents2_Event iEvent = (HTMLDocumentEvents2_Event)m_pHtmlDoc2;
                //iEvent.onclick += new HTMLDocumentEvents2_onclickEventHandler(iEvent_onclick);
                //iEvent.oncontextmenu += new HTMLDocumentEvents2_oncontextmenuEventHandler(ContextMenuEventHandler);
                //MessageBox.Show(webBrowser1.ReadyState.ToString() + "DocumentCompleted");


            }
        }
        protected Dictionary<string, object> RepostList = new Dictionary<string, object>();

        protected object GetRepost(string type)
        {
            string typeName = string.Concat("Advertise.Repost", type);
            if (!RepostList.ContainsKey(type))
            {
                Assembly asm = Assembly.GetExecutingAssembly();

                object[] parameters = new object[2];
                parameters[0] = webBrowser1;
                parameters[1] = xmlHelper;
                Object obj = asm.CreateInstance(typeName, true, BindingFlags.Default, null, parameters, null, null);
                RepostList.Add(type, obj);
            }
            return RepostList[type];
           
        }

        #region 监听webBrowser事件
        void Document_Click(object sender, HtmlElementEventArgs e)
        {
            //MessageBox.Show(e.EventType);
            //MessageBox.Show(e.FromElement.Id + e.FromElement.InnerHtml);

        }

        void webBrowser1_NewWindow(object sender, CancelEventArgs e)
        {
            //e.Cancel = true;
        }

        protected void Window_Error(object sender, HtmlElementErrorEventArgs e)
        {
            e.Handled = true;
        }

        public bool iEvent_onclick(IHTMLEventObj pEvtObj)
        {
            //MessageBox.Show(pEvtObj.qualifier);
            return true;
        }
        // 事件处理函数,目的，不使用WebBrowser自己的菜单。 
        private bool ContextMenuEventHandler(IHTMLEventObj e)
        {
            MessageBox.Show("ContextMenuEventHanderl");
            return false;
        }

       
        
        protected void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
        {
            //MessageBox.Show(webBrowser1.ReadyState.ToString());
            webBrowser1.ScriptErrorsSuppressed = false;
            HtmlDocument hd = webBrowser1.Document;
            IHTMLWindow2 win = (IHTMLWindow2)hd.Window.DomWindow;
            string s = @"function confirm() {";
            s += @"return true;";
            s += @"}";
            s = @"function killerrors() { return true; } window.onerror = killerrors; ";

            s += @"function alert() {};";
            s += @"window.onbeforeunload = function(){};";

            s += "window.alert = null; window.confirm = null;window.open = null;window.showModalDialog = null;";
            win.execScript(s, "javascript");
        }
        #endregion

        private void btnRequest_Click(object sender, EventArgs e)
        {

        }

        private void btnReg_Click(object sender, EventArgs e)
        {
            FrmReg fm = new FrmReg();
            fm.Show();
        }

        private void btnOpenUserList_Click(object sender, EventArgs e)
        {
            frmUserList frmuserList = new frmUserList();
            frmuserList.Show();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (timer.Enabled == true)
            {
                timer.Enabled = false;
                btnStop.Text = "恢复";
            }
            else
            {
                timer.Enabled = true;
                btnStop.Text = "停止";
            }
        }

        private void btnFaile_Click(object sender, EventArgs e)
        {
            if (FailRegeistEntitys.Count > 0)
            {
                regeistEntitys = FailRegeistEntitys;
                timer.Enabled = true;
                state = 0;
            }
            else
            {
                MessageBox.Show("没有发送失败");
            }
           
        }

        private void FrmReport_Resize(object sender, EventArgs e)
        {
           // ShoveToBackground();
        }

        private void FrmReport_Activated(object sender, EventArgs e)
        {
            //ShoveToBackground();
        }

        private void btnJump_Click(object sender, EventArgs e)
        {
            updateInfo.Index++;
            btnJump.Text = "跳过(" + updateInfo.Index.ToString() + ")";
        }

    


    }
    public class UpdateInfo
    {
        public int Count { get; set; }
        public int Index { get; set; }
        public string Content { get; set; }
    }

    class EWebBrowser : System.Windows.Forms.WebBrowser
    {
        SHDocVw.IWebBrowser2 Iwb2;

        protected override void AttachInterfaces(object nativeActiveXObject)
        {
            Iwb2 = (SHDocVw.IWebBrowser2)nativeActiveXObject;
            Iwb2.Silent = true;
            base.AttachInterfaces(nativeActiveXObject);
        }

        protected override void DetachInterfaces()
        {
            Iwb2 = null;
            base.DetachInterfaces();
        }
    }
}
